<?php
/**
 * Created by PhpStorm.
 * User: qishengqiang
 * Date: 2021-04-30
 * Time: 11:12
 */

namespace app\applet\controller;


use app\applet\BaseController;
use app\models\Areas;
use app\models\Cities;
use app\models\Provinces;
use think\facade\Cache;


class ProvinceController extends BaseController
{
    public function indexAction()
    {
        $provinces = Provinces::select();

        $data = [];

        $data = json_decode(Cache::get('province_lists'), 1);

        if (empty($data)) {
            foreach ($provinces as $key => $province) {
                $data[$key] = [
                    'code' => $province->provinceCode,
                    'name' => $province->provinceName,
                    'citylist' => []
                ];
                $cities = Cities::where(['provinceId' => $province->provinceId])->select();

                if (count($cities)) {
                    foreach ($cities as $k => $city) {
                        $data[$key]['citylist'][$k] = [
                            'code' => $city->cityCode,
                            'name' => $city->cityName,
                            'arealist' => []
                        ];
                        $areas = Areas::where(['cityId' => $city->cityId])->select();

                        if (count($areas)) {
                            foreach ($areas as $k1 => $area) {
                                $data[$key]['citylist'][$k]['arealist'][$k1] = [
                                    'code' => $area->areaCode,
                                    'name' => $area->areaName
                                ];
                            }
                        }
                    }
                }
            }

            Cache::set('province_lists', json_encode($data, JSON_UNESCAPED_UNICODE));
        }

        return json()->data(['code' => 200, 'msg' => '查询成功', 'data' => $data]);
    }
}